﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 仓库管理
    /// </summary>
    [ControllerGroup(groupName: "Store", useage: "仓库管理-仓库管理")]
    public class StoreController : BaseController
    {
        JWTPlayloadInfo playload;
        readonly StoreBll _instance;
        /// <summary>
        /// 构造函数
        /// </summary>
        public StoreController()
        {
            _instance = StoreBll.Instance;
        }

        /// <summary>
        /// 查询树形数据
        /// </summary>
        /// <param name="search">仓库名称</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetTreeList(string search = "")
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(search))
            {
                strWhere += " and StoreName like '%" + search + "%' ";
            }

            List<Store> list = _instance.GetListModels(strWhere, "CreateTime");

            if (list.Count > 0)
            {
                return JsonHelper.SuccessJson(_instance.GetTreeJson(list));
            }
            else
            {
                return JsonHelper.NullJson("没有数据！");
            }
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                Store model = _instance.GetModelById(ID);
                if (model != null)
                {
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 查询所有仓库
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetParentStore()
        {
            string strWhere = " and Type ='1' ";

            List<Store> list = _instance.GetListModels(strWhere, "CreateTime");

            if (list != null && list.Count > 0)
            {
                return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
            }
            else
            {
                return JsonHelper.NullJson("没有数据！");
            }
        }

        /// <summary>
        /// 查询所有库区
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetStoreArea()
        {
            string strWhere = " and Type ='2' ";

            List<Store> list = _instance.GetListModels(strWhere, "CreateTime");

            if (list != null && list.Count > 0)
            {
                return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
            }
            else
            {
                return JsonHelper.NullJson("没有数据！");
            }
        }

        /// <summary>
        /// 新增仓库/库区
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddStore([FromBody] Store model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    //默认字段
                    model.IsDelete = 0;
                    model.Status = 1;
                    model.CreateTime = DateTime.Now;
                    int res = _instance.AddStore(model);
                    if (res > 0)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "新增" + model.Type, Constant.ActionEnum.Add, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "新增" + model.Type, Constant.ActionEnum.Add, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "新增仓库" + ex.Message, Constant.ActionEnum.Add, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改仓库信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStore([FromBody] Store model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (model.ID <= 0)
                {
                    return JsonHelper.ErrorJson("参数错误");
                }
                bool isExist = _instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    int res = _instance.UpdateStore(model);
                    if (res > 0)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "修改" + model.Type, Constant.ActionEnum.Edit, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "修改" + model.Type, Constant.ActionEnum.Edit, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("修改失败");

                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "修改仓库:" + ex.Message, Constant.ActionEnum.Edit, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除仓库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteStore(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];

            try
            {
                if (id <= 0)
                {
                    return JsonHelper.ErrorJson("参数错误");
                }
                Store model = _instance.GetModelById(id);
                if (model == null)
                {
                    return JsonHelper.ErrorJson("数据不存在");
                }

                // 什么情况下不允许删除（仓库使用中，存在下级）

                bool result = _instance.DeleteStore(id);
                if (result)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "删除" + model.Type, Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson("删除成功");
                }
                else
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "删除" + model.Type, Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                    return JsonHelper.FailJson("删除失败");

                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, "删除仓库:" + ex.Message, Constant.ActionEnum.Delete, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStatus(int id, int status)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];

            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            if (status != 1 && status != 2)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            Store model = _instance.GetModelById(id);
            if (model == null)
            {
                return JsonHelper.ErrorJson("数据不存在");
            }

            string strStatus = status == 1 ? "启用" : "禁用";
            if(model.Type == "1")
            {
                strStatus += "仓库";
            }
            if(model.Type == "2")
            {
                strStatus += "库区";
            }

            try
            {
                bool result = _instance.UpdateStatus(id, status);
                if (result)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, strStatus, Constant.ActionEnum.Enabled, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson(strStatus + "成功");
                }
                else
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, strStatus, Constant.ActionEnum.Enabled, Constant.StatusEnum.Fail));
                    return JsonHelper.FailJson(strStatus + "失败");

                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Store, strStatus + ":" + ex.Message, Constant.ActionEnum.Enabled, Constant.StatusEnum.Exception), ex);
                throw ex;
            }

        }

    }
}
